package com.wedo.mall.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.e.library.activity.EActivity;
import com.e.library.fragment.EFragment;
import com.e.library.http.EApi;
import com.e.library.http.EClient;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.utils.EUtils;
import com.wedo.mall.R;
import com.wedo.mall.activity.ProtocolActivity;
import com.wedo.mall.activity.register.AgentInfoActivity;
import com.wedo.mall.dialog.RegionalPopup;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindDrawable;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * 注册
 * Created by e on 2017/7/2.
 */

public class RegisterFragment extends EFragment<EActivity> {

    @BindView(R.id.et_username) EditText et_username;
    @BindView(R.id.et_password) EditText et_password;
    @BindView(R.id.et_check_code) EditText et_check_code;
    @BindView(R.id.et_referee) EditText et_referee;
    @BindView(R.id.btn_check_code) Button btn_check_code;

    @BindView(R.id.et_phone) EditText et_phone;

    @BindString(R.string.register_vc_resend) String register_vc_resend;
    @BindString(R.string.register_region_format) String register_region_format;


    /**是否是商家：0表示普通用户，1表示商家*/
    private int status = 0;

    public static RegisterFragment with(){
        return new RegisterFragment();
    }

    /**商家注册*/
    public RegisterFragment agent(){
        this.status = 1;
        return this;
    }

    @Override
    protected int layout() {
        return R.layout.fragment_register_2;
    }

    @Override
    protected void onFragmentCreated(View contentView, Bundle bundle) {
        tel();
    }

    @OnClick(R.id.tv_username)
    protected void onUsernameClick(TextView tv){
        new RegionalPopup(getContext()).show(tv);
    }

    @OnClick(R.id.btn_protocol)
    protected void onProtocolClick() {
        activity().toActivity(ProtocolActivity.class);
    }

    /**获取验证码*/
    @OnClick(R.id.btn_check_code)
    protected void onCheckCodeClick(){

        String account = et_username.getText().toString();
        if(!validation(account)) {
            return;
        }
        activity().loading();
        Observable<EResponse> observable = EClient.with().api().verifyCode(account,"0");
        EClient.with().observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                mTimer.start();
                if(status == 1) {//2018/2/1 商家注册不需要发送验证码，显示随机验证码
                    et_check_code.setText(response.string("code"));
                }else {
                    activity().dismiss(R.string.register_vc_send);
                }
            }

            @Override
            public void failure(String msg) {
                activity().dismiss(msg);
            }
        });

    }

    /**注册*/
    @OnClick(R.id.btn_register)
    protected void onRegisterClick(){
        String account = et_username.getText().toString();
        if(!validation(account)) {
            return;
        }

        String password = et_password.getText().toString();
        if (TextUtils.isEmpty(password)){
            activity().toast(R.string.register_password_enter);
            return;
        }

        if (password.length() <6 || password.length() >12){
            activity().toast(R.string.register_password_hint);
            return;
        }

        String code = et_check_code.getText().toString();
        if(TextUtils.isEmpty(code)) {
            activity().toast(R.string.register_vc_hint);
            return;
        }

        String phone = et_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)){
            activity().toast(R.string.register_phone_enter);
            return;
        }

        Map<String,String> params = new HashMap<>(5);
        params.put("email",account);
        params.put("phone",phone);
        params.put("password",password);
        params.put("verify",code);
        params.put("status",String.valueOf(status));

        String referrer = et_referee.getText().toString();
        if(!TextUtils.isEmpty(referrer)) {
            params.put("referrer",referrer);
        }

        activity().loading();
        Observable<EResponse> observable = EClient.with().api().post(EApi.LOGIN_REGISTER,params);
        EClient.with().observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                activity().dismiss(R.string.register_success);
                if(status == 0) {
                    activity().defaultFinish();
                }else {
                    /**商家注册完成之后，跳转到补充材料页面*/
                    String userId = response.string("userId");
                    Bundle bundle = new Bundle();
                    bundle.putString("userId",userId);
                    activity().toActivity(AgentInfoActivity.class,bundle);
                    activity().defaultFinish();
                }
            }

            @Override
            public void failure(String msg) {
                activity().dismiss(msg);
            }
        });

    }

    /**验证注册账号*/
    private boolean validation(String account){
        if (TextUtils.isEmpty(account)){
            activity().toast(R.string.register_email_enter);
            return false;
        }

        if (!EUtils.isEmail(account)){
            activity().toast(R.string.register_email_invalid);
            return false;
        }

        return true;
    }

    private CountDownTimer mTimer = new CountDownTimer(60*1000,1000) {
        @Override
        public void onTick(long millis) {
            if (isDetached()) return;
            btn_check_code.setClickable(false);
            btn_check_code.setText(String.format(register_vc_resend,millis/1000));
        }

        @Override
        public void onFinish() {
            if (isDetached()) return;
            btn_check_code.setClickable(true);
            btn_check_code.setText(R.string.register_get_vc);

        }
    };

    @Override
    public void onDestroy() {
        mTimer.cancel();
        mTimer = null;
        super.onDestroy();
    }

    @OnClick(R.id.btn_help)
    protected void onHelpClick(){
        requestPhoneCall(tel);
    }

    private String tel;
    private void tel(){
        Observable<EResponse> observable = activity().api().tel(new HashMap<String, String>(1));
        activity().observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                tel = response.string("list");
            }

            @Override
            public void failure(String msg) {

            }
        });
    }

    public static final int REQ_PHONE_CALL = 104;
    public  void requestPhoneCall(String phone){
        if(TextUtils.isEmpty(phone)) {
            activity().toast(R.string.consult_phone_invalid);
            return;
        }

        if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE},REQ_PHONE_CALL);
            return;
        }
        phoneCall(phone);
    }

    public void phoneCall(String phone){
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQ_PHONE_CALL){
            if (grantResults.length >0){
            }
        }
    }
}
